let huabu = document.querySelector('#huabu')
let tools = huabu.getContext('2d')
let x = Math.floor(Math.random()*(20))*30
let y = Math.floor(Math.random()*(20))*30
let snake = [{x:3,y:0},{x:2,y:0},{x:1,y:0}]
let directionX = 1
let directionY = 0
let num = 0
let t =null
let btnObj = document.querySelector('button:nth-of-type(3)')
let isGameOver = false
let isEated = false
document.onkeydown=function(evt){
    let e = evt || window.event
    if(e.keyCode===38){
        directionX = 0
        directionY = -1
    }else if(e.keyCode===40){
        directionX = 0
        directionY = 1
    }else if(e.keyCode===37){
        directionX = -1
        directionY = 0
    }else if(e.keyCode===39){
        directionX = 1
        directionY = 0
    }
}
document.querySelector('button:nth-of-type(1)').onclick=function(){
    clearInterval(t)
    t=setInterval(()=>{
        if(isGameOver) {
            return
        }
        tools.clearRect(0,0,600,600)
        tools.fillStyle='#cccc00'
        let oldData = snake[0]
        let newData = {
            x:oldData.x+directionX,
            y:oldData.y+directionY
        }
        if(newData.x<0||newData.y<0||newData.y>19||newData.x>19){
            isGameOver=true
            alert('游戏结束！！！')
        }else{
            
            if(snake[0].x*30 === x && snake[0].y*30 === y){
                isEated=true
                num++
                btnObj.innerText=`得分：${num}分`
    
            }else{
                isEated=false
                snake.pop()
            }
            snake.unshift(newData)
        }
        if(isEated){
            x = Math.floor(Math.random()*(20))*30
            y = Math.floor(Math.random()*(20))*30
        }
        tools.fillRect(x,y,30,30)
        for(let i =0;i<snake.length;i++){
            if(i===0){
                tools.fillStyle='red'
            }else{
                tools.fillStyle='pink'
            }
            tools.fillRect(snake[i].x*30,snake[i].y*30,30,30)
        }
        for(let i = 1;i<20;i++){
            tools.moveTo(0,30*i+0.5)
            tools.lineTo(600,30*i+0.5)
        }
        for(let i = 1;i<20;i++){
            tools.moveTo(30*i+0.5,0)
            tools.lineTo(30*i+0.5,600)
        }
        tools.strokeStyle='white'
        tools.stroke()
    },1000/3)
}
document.querySelector('button:nth-of-type(2)').onclick=function(){
    clearInterval(t)
}